#include <pthread.h>
#include <ctime>
#include <unistd.h>
#include "RingQueue.hpp"
#include "Task.hpp"


using std::cout;
using std::endl;


void *consumer(void *args)
{
    RingQueue<Task> *rq = (RingQueue<Task> *)args;
    while (true)
    {
        sleep(1);
        //  int data = 0;
        //  rq->pop(&data);
        //  cout << "Consumer: " << data << endl;
        Task t;
        rq->pop(&t);
        t();
        cout << pthread_self() << " | Consumer: " << t.formatArg() << t.formatRes() << endl;
    }
}


void *productor(void *args)
{
    RingQueue<Task> *rq = (RingQueue<Task> *)args;


    while (true)
    {
        //sleep(1);
        // int data = rand() % 10 + 1;
        // rq->push(data);
        // cout << "Productor: " << data << endl;
        int x = rand() % 20 + 1;
        int y = rand() % 10 + 1;
        char op = ops[rand() % ops.size()];
        Task t(x, y, op);
        rq->push(t);
        cout << pthread_self() << " | Productor: " << t.formatArg() << "?" << endl;
    }
}


int main()
{
    srand((unsigned int)time(nullptr) ^ getpid());
    RingQueue<Task> *rq = new RingQueue<Task>();


    pthread_t c[3], p[2];


    for(int i=0;i<sizeof(c)/sizeof(c[0]);i++)
    pthread_create(&c[i], nullptr, consumer, rq);


    for(int i=0;i<sizeof(p)/sizeof(p[0]);i++)
    pthread_create(&p[i], nullptr, productor, rq);


    for(int i=0;i<sizeof(c)/sizeof(c[0]);i++)
    pthread_join(c[i], nullptr);


    for(int i=0;i<sizeof(p)/sizeof(p[0]);i++)
    pthread_join(p[i], nullptr);


    delete rq;
    return 0;
}